const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const session = require('koa-session')

const index = require('./routes/index')
const user = require('./routes/user')
const permission = require('./routes/permission')
const loan = require('./routes/loan')
const approve = require('./routes/approve.js')
const contract = require('./routes/contract.js')
const { checkLogin } = require('./middlewares/index.js')

// 存储退出后的token
global.blackTokenList = [];

const store = {
  strorage: {},
  get(key) {
    // 也可以从数据库中读取
    return this.strorage[key]
  },
  set(key, val) {
    this.strorage[key] = val
  },
  destroy(key) {
    delete this.storage[key]
  },
}

// error handler
onerror(app)

// middlewares
app.use(bodyparser({
  enableTypes: ['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

/**
 * app.context 是从其创建 ctx 的原型。
 * 您可以通过编辑 app.context 为 ctx 添加其他属性。
 * 这对于将 ctx 添加到整个应用程序中使用的属性或方法非常有用，
 * 这可能会更加有效（不需要中间件）和/或 更简单（更少的 require()），
 * 而更多地依赖于ctx，这可以被认为是一种反模式。
 */
app.context.success = function (data) {
  this.body = {
    code: 20000,
    data
  }
}
app.context.fail = function (data) {
  this.body = {
    code: 102,
    data
  }
}
app.context.tokenExpires = function (data) {
  this.body = {
    code: 603,  // token过期，需要重定向
    data
  }
}


app.use(checkLogin)
app.use(session({ store }, app))

// routes
app.use(index.routes(), index.allowedMethods())
app.use(user.routes(), user.allowedMethods())
app.use(permission.routes(), permission.allowedMethods())
app.use(loan.routes(), loan.allowedMethods())
app.use(approve.routes(), approve.allowedMethods())
app.use(contract.routes(), contract.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
